/*获取收货地址*/

var warehouse = JSON.parse(sessionStorage.getItem("orderDetail"));


discountdata(123)
function discountdata (val) {
    if(val==123){
        //初始化 省
        var user_data = {
            level: '101',
            // memberId:'10258',
        }
        var succCallBack = function (data, status, response) {
            console.log(data)
            if(data.errorCode=="0"){
                var tab_data=data.list;
                if(tab_data==''){
                    cer+='<option value=""></option>'
                    $("#getArea").html(cer);
                }else{
                    var cer="<option value=''>请选择收货区域</option>"
                    for(var i=0; i<tab_data.length; i++){
                        cer+='<option value="'+tab_data[i].code+'">'+tab_data[i].name+'</option>'
                    }
                    $("#getArea").html(cer);
                }
            }
        };
        web.doAjax(root.member.getLowerAddress,'post',user_data, succCallBack);
    }else if(val==1){
        //市
        var special=$('#getArea').val()
        if(special==""){
            var cer="<option value=''>请选择收货位置</option>"
            $("#getPlace").html(cer);
        }else {
            var user_data = {
                level: '102',
                // memberId:'10258',
                parentCode:special
            }
            var succCallBack = function (data, status, response) {
                if(data.errorCode=="0"){
                    var tab_data=data.list;
                    if(tab_data==''){
                        cer+='<option value=""></option>'
                        $("#getPlace").html(cer);
                    }else{
                        var cer="<option value=''>请选择收货位置</option>"
                        for(var i=0; i<tab_data.length; i++){
                            cer+='<option value="'+tab_data[i].code+'">'+tab_data[i].name+'</option>'
                        }
                        $("#getPlace").html(cer);
                    }
                }
            };
            web.doAjax(root.member.getLowerAddress,'post',user_data, succCallBack);
        }
    }
}
/*表格渲染*/
var dataSource = new Array();
//table的数据源
var table; //table对象
dataSource = [];

function orderList(data) {
	dataSource.splice(0, dataSource.length); //清空数组
	if (data.data != null && data.data != "") {
		var datashu = data.data.startIndex + 1;
		$.each(data.data.result, function (i, field) {
			var datashus = datashu++
			var rowData = new Array();
			rowData.push(field.order_id);
			rowData.push(field.platform);
			rowData.push(field.anomal_type);
			rowData.push(field.created_at);
			rowData.push(field.customer_name);
			/*多个授权收货人
            rowData.push(field.listAddressReceiver);*/
			if (field.listAddressReceiver != null) {
				rowData.push(field.listAddressReceiver[0]);
			}
			rowData.push(field.paid_type);
			rowData.push(field.paid_amount);
			rowData.push(field.order_status);
			rowData.push(field.received_phone);
			rowData.push(field.login_account);
			rowData.push(datashus);
			rowData.push(field.orderChildIds);
			rowData.push(field.products);//商品信息
			dataSource.push(rowData);
		});

	}
	initDataTable(dataSource);
}
var anomaltypeall={
	"10": "大额订单", "20": "临采商品订单", "30": "超赊欠额度订单", "40": "货到付款订单", "50": "代客下单异常订单", "60": "超卖订单", "70": "低于成本价订单", "80": "erp拦截订单",
	"90": "经纬度异常", "100": "分销订单", "110": "门店付款", "120": "账期扣额度失败", "130": "厂家直送订单", "140": "缺货超4吨/5方", "150": "预计送达时间晚于期望送达时间","200":"OMS分区域上线"
}
var paidtypes={
	'1001': "在线支付", '1002': "支付宝支付", '1003': "微信支付", '1101': "货到付款", '1102': "货到付款-现金", '1103': "货到付款-pos机", '1201': "账期支付",
	'1301': "银行转账", '1401': "银行汇票", '1601': "积分支付", '1701': "门店付款"
}
function initDataTable(dataSource) {
		var outHtml = '';
		for(var i=0;i<dataSource.length;i++){
			var curData= dataSource[i];
			var platFormStr = ""
			switch (curData[1]) {
				case 10:
					platFormStr ="普通平台";
					break;
				case 20:
					platFormStr = "签约平台";
					break;
				case 40:
					platFormStr = "对接平台";
					break;
			}

			var inquiryStr = '';
			var productData = curData[13];
			var productStr = '';
			var curProLen = productData ? productData.length : 1;
			//异常类型
			var abnormalType = "";
			var abnormalTypeArr = [];
			var rowArr = curData[2].split(',');
			for(var k = 0; k < rowArr.length; k++) {
				abnormalTypeArr.push(anomaltypeall[rowArr[k]]);
			}
			for(var h = 0; h < abnormalTypeArr.length; h++) {
				if(h < abnormalTypeArr.length - 1) {
					abnormalType += abnormalTypeArr[h] + ",";
				} else {
					abnormalType += abnormalTypeArr[h] + "";
				}
			}
			//收货人
			var receivernames=""
			if (curData[5]==null ||curData[5].receiver_name==undefined){
				receivernames=""
			}else{
				receivernames=curData[5].receiver_name
			}
			var state = "";
			switch (curData[8]) {
				case 9:
					if (curData[6]==1101){
						state = "待审核";
						break;
					}else {
						state = "待付款";
						break;
					}
				case 10:
					state = "待付款";
					break;
				case 20:
					state ="待审核";
					break;
				case 30:
					state = "待配货";
					break;
				case 40:
					state = "待出库";
					break;
				case 50:
					state = "待发货";
					break;
				case 60:
					state = "待收货";
					break;
				case 70:
					state = "已收货，待结算";
					break;
				case 80:
					state = "订单成功";
					break;
				case 90:
					state ="订单完成";
					break;
				case 100:
					state ="已取消";
					break;
				case 110:
					state = "交易关闭";
					break;
			}
			var valall=""
			if (curData[12]!=""&&curData[12]!=null) {
				valall = '<span class="powerButton 102"><a onclick="abnormalOrderInfo(\'异常订单详情\',\'abnormalOrder-info.html\',\'' + curData[0] + '\')">订单详情</a></span><br><span class="powerButton 102"><a onclick="viewSuborder(\'' + curData[0] + '\')">查看子订单</a></span>';

			}else {
				valall = '<span class="powerButton 102"><a onclick="abnormalOrderInfo(\'异常订单详情\',\'abnormalOrder-info.html\',\'' + curData[0] + '\')">订单详情</a></span>';

			}

			inquiryStr+= '<td width="115" rowspan="'+curProLen+'">'+abnormalType+'</td>'+
				'<td width="70" rowspan="'+curProLen+'">'+isUndefined(curData[4])+'</td>'+
				'<td width="70" rowspan="'+curProLen+'">'+receivernames+'</td>'+
				'<td width="70" rowspan="'+curProLen+'">'+paidtypes[curData[6]]+'</td>'+
				'<td width="70" rowspan="'+curProLen+'">'+(curData[7]).toFixed(2)+'</td>'+
				'<td width="70" rowspan="'+curProLen+'">'+state+'</td>'+
				'<td width="100" rowspan="'+curProLen+'">'+valall+'</td>';


			var showMoreHtml = '';
			if(curProLen>3){
				showMoreHtml = '<div class="list_more " onclick="showMore(this);"><a href="javascript:void(0);">查询了<span id="list_length">'+curProLen+'</span>件商品  <span id="operText">更多</span><i class="icon"></i></a></div>'
			}
			if(productData && productData.length>0){
				for(var j=0;j<productData.length;j++){
					var curPro = productData[j];
					if(j!=0){
						inquiryStr = '';
					}

					var isHideClass = '';
					if(j>=3){
						isHideClass = 'moretr hide';
					}

					productStr +='<tr class="'+isHideClass+'">'+
						'<td onclick="skipGoodsDetails(' + curPro.spu_id + ')" width="75" rowspan="1"><img style="width:60px;height:60px;" src="' + imgSize(curPro.product_pic) + '"/></td>'+
						'<td width="135" rowspan="1"><div>' + curPro.sku_code + '</div><div>' + curPro.product_name + '</div><div>' + curPro.color + '</div><div>' + curPro.sku_info + '</div></td>'+
						'<td width="75" rowspan="1"><span>X</span>' + curPro.buyyer_count + '' + curPro.unit_name + '</td>'+  inquiryStr +
						'</tr>';

				}


			}else{
				productStr +='<tr>'+
					'<td width="75" rowspan="1"></td>'+
					'<td width="135" rowspan="1"></td>'+
					'<td width="75" rowspan="1"></td>'+  inquiryStr +
					'</tr>';
			}

			outHtml+= '<div class="orer_item"><div class="list_box list_over">'+
				'<div class="title">'+
				'<span>订单号：'+isUndefined(curData[0])+'</span>'+
				'<span>下单时间：'+timeIsDefault(curData[3])+'</span>'+
				'<span>订单来源：'+platFormStr+'</span>'+
				'</div>'+
				'<table style="width:100%;" class="table table-border table-bg table-sort list_box_table"><tbody>'+productStr+'</tbody></table></div>'+showMoreHtml+'</div>';
		}

		$('#orderList').empty().append(outHtml);
        //权限控制函数
        power()
}

function isUndefined(dt){
	var str = dt ? dt : '';
	return str;
}
function timeIsDefault(tm){
	var str = tm == '1000-01-01 00:00:00' ? '' : tm;
	return str;
}
//更多
function showMore(dom, length,status) {
	var curDom = $(dom);
	var curTr = curDom.parents('.orer_item').find('.moretr');
	if(curTr.eq(0).hasClass('hide')){
		curTr.removeClass('hide');
		curDom.find('#operText').html('收起');
	}else{
		curTr.addClass('hide');
		curDom.find('#operText').html('更多');
	}

}

function getList(page_num) {
	$("#area").val()
	$.ajax({
		contentType: "application/json",
		type: "POST",
        //url:"http://192.168.65.116:7090/aorder/anomal/queryAnomalOrder",
		url: root.orderInter.order_queryAnomalOrder,
		cache: false, //禁用缓存
		dataType: "json",
		data: JSON.stringify({
            anomal_type: $("#abnormalType").val(),//异常类型
			created_address_code: $("#area").val(), //地区
			warehouse_id: $("#shippingWarehouse option:selected").val(), // 仓库id
			order_id: $("#orderCode").val(), // 订单编号
			sales_manager_name: $("#saleManager").val(), //销售经理
			paid_type: $("#payWay").val(), //支付方式
			search_param: $("#SKUCode").val(), //SKU码/code码
			customer_name: $("#buyerName").val(), //客户名称
			created_at_begin: $("#timemin").val(), //下单开始时间
			created_at_end: $("#timemax").val(), //下单结束时间
            receiver_name: $("#consignee").val(), //收货人姓名
            mobile: $("#phoneNum").val(), //收货人电话
            receiver_province: $("#getArea").val(),// 一级收货地（收货区域）
            receiver_city: $("#getPlace").val(),// 二级收货地（收货位置）
			page_num: page_num, //当前页码
			page_size: 50, //每页显示条数
            role_name: $("#orderPlacer").val(),//代客下单人
            platform:$("#platform").val(),//订单来源
            final_sent_type:$("#final_sent_type").val(),//配送方式
			companys_ids:sessionStorage.getItem("organizationWarehouse"),//公司对应的发货仓id
			warehouse_ids:sessionStorage.getItem("regions"),//仓库权限串
			belong_groupIds:sessionStorage.getItem("companys"),//销售归属权限串
			sales_manager_ids:sessionStorage.getItem("personnels"),//销售经理权限串
			"order_split_status":$("#order_split_status").val(),
			mainCustomerType:$("#CustomerType").val(),
			"commonOrderTypeList":typeIdOnearry,
		}),
		success: function(result) {
			sessionStorage.setItem("abstatus",'')
			console.log(result)
			orderList(result);
			var totalPages=0
			if(result.data!=null&&result.data!=""){
				totalPages=result.data.totalPage
			}else {
				totalPages=0
			}
			$('.M-box3').pagination({

				pageCount: totalPages,
				jump: true,
				coping: true,
				prevContent: '上页',
				nextContent: '下页',
				callback: function(api) {
					console.log(api.getCurrent());
					$.ajax({
						contentType: "application/json",
						type: "POST",
                        //url:"http://192.168.65.116:7090/aorder/anomal/queryAnomalOrder",
						url: root.orderInter.order_queryAnomalOrder,
						cache: false, //禁用缓存
						dataType: "json",
						data: JSON.stringify({
                            anomal_type: $("#abnormalType").val(),//异常类型
                            created_address_code: $("#area").val(), //地区
                            warehouse_id: $("#shippingWarehouse option:selected").val(), // 仓库id
                            order_id: $("#orderCode").val(), // 订单编号
                            sales_manager_name: $("#saleManager").val(), //销售经理
                            paid_type: $("#payWay").val(), //支付方式
                            search_param: $("#SKUCode").val(), //SKU码/code码
                            customer_name: $("#buyerName").val(), //客户名称
                            created_at_begin: $("#timemin").val(), //下单开始时间
                            created_at_end: $("#timemax").val(), //下单结束时间
                            receiver_name: $("#consignee").val(), //收货人姓名
                            mobile: $("#phoneNum").val(), //收货人电话
                            receiver_province: $("#getArea").val(),// 一级收货地（收货区域）
                            receiver_city: $("#getPlace").val(),// 二级收货地（收货位置）
                            page_num: api.getCurrent(), //当前页码
                            page_size: 50, //每页显示条数
                            role_name: $("#orderPlacer").val(),//代客下单人
                            platform:$("#platform").val(),//订单来源
                            final_sent_type:$("#final_sent_type").val(),//配送方式
							companys_ids:sessionStorage.getItem("organizationWarehouse"),//公司对应的发货仓id
							warehouse_ids:sessionStorage.getItem("regions"),//仓库权限串
							belong_groupIds:sessionStorage.getItem("companys"),//销售归属权限串
							sales_manager_ids:sessionStorage.getItem("personnels"),//销售经理权限串
							mainCustomerType:$("#CustomerType").val(),
							"commonOrderTypeList":typeIdOnearry,
						}),
						success: function(result) {
							console.log(result)
							orderList(result);
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							alert(XMLHttpRequest);
						}
					});
				}
			});
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert(XMLHttpRequest);
		}
	});
}
/*跳转异常订单详情*/
function abnormalOrderInfo(title, url, data) {
	console.log(data);
	sessionStorage.setItem("orderId", data);
	var index = layer.open({
		type: 2,
		title: title,
		content: url
	});
	layer.full(index);
	$("#viewSuborder").modal("hide");
}
//弹框跳转
var abstatus= sessionStorage.getItem("abstatus")
console.log(abstatus)
if(abstatus==10){
	getList(1)
}

//查看子订单
function viewSuborder(val) {
	$("#viewSuborder").modal("show");
	$.ajax({
		contentType: "application/json",
		type: "POST",
		url: root.orderInter.order_queryAnomalOrder,
		cache: false, //禁用缓存
		dataType: "json",
		data: JSON.stringify({
			order_id: val, // 订单编号
			page_num: 1, //当前页码
			page_size: 50, //每页显示条数
			companys_ids:sessionStorage.getItem("organizationWarehouse"),//公司对应的发货仓id
			warehouse_ids:sessionStorage.getItem("regions"),//仓库权限串
			belong_groupIds:sessionStorage.getItem("companys"),//销售归属权限串
			sales_manager_ids:sessionStorage.getItem("personnels"),//销售经理权限串
		}),
		success: function(result) {
			var viewSubordertale=""
			var datas=result.data.result;
			for(var k=0;k<datas.length;k++) {
				if(datas[k].orderChildIds!=null){
					for (var i = 0; i < datas[k].orderChildIds.length; i++) {
						viewSubordertale += ' <div class="clearfix">' +
							' <label>子订单：</label><a class="formControls w-150 ml-10 lh-26" onclick="abnormalOrderInfo(\'异常订单详情\',\'abnormalOrder-info.html\',\'' + datas[k].orderChildIds[i] + '\')">' + datas[k].orderChildIds[i] + '</a>' +
							'</div>';

					}
				}

			}
			$("#viewSuborders").html(viewSubordertale)
		},

	});
}
//关闭
function closeodel() {
	$("#viewSuborder").modal("hide");
}

//获取客户组类型
getCustomerType()
function getCustomerType(){
	$.ajax({
		url: root.orderInter.order_custromTy,
		// url: 'http://192.168.252.17:7777/amembership/mainCustomer/mainCustomerType',
		type: "GET",
		cache: false, //禁用缓存
		contentType: "application/json",
		dataType: "json",
		data: {},
		success:function(result){
			let arr = Object.entries(result.data).map(item => ({name:item[1],value:item[0]}))
			let option = `<option value="">请选择</option>`
			arr.forEach((item) => {
				option += `
					<option value="${item.value}">${item.name}</option>
				`
			})
			$('#CustomerType').append(option)
			
		},error:function(error){
			console.log(error)
		}
	})
}

//正常商品跳转到前台商品详情
function skipGoodsDetails(code) {
    if (!code) {
        return false;
    }
    var index = layer.open({
        type: 2,
        title: "商品详情",
        content: "https://" + window.location.host + "/productspu/" + code +".html"
    });
    layer.full(index);
}
//订单类型
var type02html =[];//存放多选时的html
var type02htmlinit =[];
var typeIdOnearry =[];//存放多选时的crmCustomerid
var typespanhtml = '';
var typeIdOne='';
$(".typeulbox2").css('display','none');
/*点击 项目 显示下拉 选项,其中全选全不选，要做传值的处理*/
$(".datava2,.icon_arrow").on('click',function (e) {
	$(this).parent().children(".icon_arrow").toggleClass("icon_arrow_down");
	if($('.typeulbox2').css("display") == "none"){
		$('.typeulbox2').show();
		if($(".typeplaceholder").find(".all-radiustype")&&$(".typeplaceholder").find(".all-radiustype").html()=="全部"){
			$(".typeplaceholder").html("")

		}
	}else{
		$(".typeulbox2").hide();
		if ($(".typeplaceholder").html()==""){
			$(".typeplaceholder").html('<span class="all-radiustype">全部</span>')
		}
	}
	/*------------------8.24 如果已经有选择过的--------------------*/
	var initcustomerId =[];
	type02htmlinit=[]
	$.each($(".typelidata"),function (index,itm) {

		initcustomerId.push($(itm).attr('crmCustomerId'))
		type02htmlinit.push($(itm).attr('crmCustomername'))
	})
	if(typeIdOnearry.length >0){
		function isArray(str){
			return Object.prototype.toString.call(str) == "[object Array]";
		}
		if(isArray(typeIdOnearry)){
			typeIdOnearry= [typeIdOnearry].join().split(',');
		}else{
			typeIdOnearry= [typeIdOnearry].join().split(',');
		}
		$.each($(".typelidata"),function (index,itm) {
			$.each(typeIdOnearry,function (i,item) {
				$.each(initcustomerId,function (j,ite) {
					if(item == ite){
						if($("itm").attr('crmcustomerid')==item){
							$(".typelidata").find('.typeevetyipt').prop('checked',true);
						}
					}
				})
			})
		})

	}
	e.stopPropagation();
});

var checkednum2=0;
//当点击下拉数据时 回显在input里面
var htmlspan2='';
$(".typeulbox2").on('click','input.typeevetyipt',function (e) {
	if($(".typeplaceholder").find(".all-radiustype")&&$(".typeplaceholder").find(".all-radiustype").html()=="全部"){
		$(".typeplaceholder").html("")

	}
	e.stopPropagation();
	if($(this).prop('checked')){
		$(this).prop('checked',true);//选中
		checkednum2 ++;
		typespanhtml=$(this).next().html();
		type02html.push(typespanhtml);
		typeIdOne = $(this).parent().attr('crmCustomerId');
		typeIdOnearry.push(typeIdOne);
		$.each(type02html,function(i,item){
			htmlspan2 = '<span>'+item+'</span>'
		})
		$(".typeplaceholder").append(htmlspan2);
		if($(".typeulbox2").find('input.typeevetyipt').length == checkednum2){
			$(".typecheckboxall").prev().prop('checked',true);
		}
		//全选反选时会用
		if (checkednum2==0) {
			$(".typecheckboxall").prev().prop('checked',true);

		}
		//判断如果只选择了一个下拉选项 在input 里面应该展示全部的名称
		onenameadd()
	}else{
		checkednum2 --;
		$(this).prop('checked',false);
		var checkfalsehtml =  $(this).next().html();
		var tt =$(this).parent().attr('crmCustomerId');
		for (var i=0;i<typeIdOnearry.length;i++){
			if(typeIdOnearry[i] == tt){
				typeIdOnearry.splice(typeIdOnearry.indexOf(tt),1);
			}
		}
		var iptspandata = $('.typeplaceholder span');//点击选中回显在span 里面的值
		$.each(iptspandata,function (i,item) {
			if($(item).html() == checkfalsehtml){
				$(item).html('');
				$(item).remove();
			}
		});
		type02html.splice($(this).next().html(),1);
		if($(".typeulbox2").find('input.typeevetyipt').length != checkednum2){
			$(".typecheckboxall").prev().prop('checked',false);
		}
		onename();
	}
});
//可点击空白处
$(document).click(function() {
	$(".typeulbox2").css('display','none');
	if ($(".typeplaceholder").html()==""){
		$(".typeplaceholder").html('<span class="all-radiustype">全部</span>')
	}
});
function onenameadd(){
	//判断如果只选择了一个下拉选项 在input 里面应该展示全部的名称
	if(typeIdOnearry.length == 1){
		$(".typeplaceholder span").css('max-width','none');
		$(".typeplaceholder span").attr('title',$(".typeplaceholder span").html());
	}else{
		$(".typeplaceholder span").css('max-width','48px');
	}
}
function onename(){
	//判断如果只选择了一个下拉选项 在input 里面应该展示全部的名称
	if(typeIdOnearry.length == 1){
		$(".typeplaceholder span").css('max-width','none');
		$(".typeplaceholder span").attr('title',$(".typeplaceholder span").html());
	}
}

/*点击全选 联动 传值*/
var typeulboxli2 = $(".typeulbox2").find('li');
$(".typecheckboxall").parent().on('click','input',function (e) {
	e.stopPropagation();
	if($(this).prop('checked')){//全选
		$(this).prop('checked',true);
		typeulboxli2.find('input').prop('checked',true);
		$(".typeplaceholder").html("")
		type02html =type02htmlinit;
		var htmlspan2='';
		$.each(type02html,function(i,item){
			htmlspan2 += '<span>'+item+'</span>'
		});
		var crmCustomerIds=$(this).attr('crmCustomerId')
		typeIdOnearry=crmCustomerIds.split(",")
		$(".typeplaceholder").append(htmlspan2);
	}else{//全不选
		$(this).prop('checked',false);
		typeulboxli2.find('input').prop('checked',false);
		typeIdOnearry=[];
		type02html=[];
		$(".typeplaceholder").html('');
	}
});
$(".typeulbox2").on('click','.typecheckboxall',function (e) {
	e.stopPropagation();
	if(  $(this).parent().find('input').prop('checked') == false){//全选
		$(this).parent().find('input').prop('checked',true);
		typeulboxli2.find('input').prop('checked',true);
		type02html =type02htmlinit;
		var htmlspan2='';
		$.each(type02html,function(i,item){
			htmlspan2 += '<span>'+item+'</span>'
		});
		$(".typeplaceholder").append(htmlspan2);
	}else{//全不选
		$(this).parent().find('input').prop('checked',false);
		typeulboxli2.find('input').prop('checked',false);
		typeIdOnearry=[];
		type02html=[];
		$(".typeplaceholder").html('');
	}
})
//重置
$('#resets').on('click', function () {
	type02html=[]
	typeIdOnearry=[]
	$(".typeplaceholder").html("")
})